import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from '@/views/user/LoginView.vue'
import MainView from '@/views/user/MainView.vue'
import WelcomeView from '@/views/user/WelcomeView.vue'
import Account from '@/views/user/AccountView.vue'
import {Message} from "element-ui";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'LoginView',
    component: LoginView
  },
  {
    path: '/main',
    name: 'MainView',
    component: MainView,
    children: [
      {path: '/welcome', name: 'WelcomeView', component: WelcomeView},
      {path: '/account', name: 'AccountView', component: Account},
      
    ]
  }
]

const router = new VueRouter({
  routes
})

// 添加路守卫
router.beforeEach(async (to, from, next) => {
  // 按官网提供的示例，做修改
  let token = sessionStorage.getItem("token");
  console.log(token)
  console.log("上一个视图",  from )
  console.log("要访问的视图名：" + to.name)
  if (token == null && to.name != 'LoginView') {
    console.log("---- 前端守卫，拦截没有登录 ----")
    Message({
      type: "error",
      message: "对不起，请先登录",
      duration: 1000
    })
    // 将用户重定向到登录页面
    return {name: 'LoginView'}
  }
  next();
})

export default router
